package com.itheima.skyserver.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.skyserver.context.BaseContext;
import com.itheima.skyserver.exception.PasswordNotMatchException;
import com.itheima.skyserver.exception.UsernameNotExistException;
import com.itheima.skyserver.mapper.EmployeeMapper;
import com.itheima.skyserver.pojo.domain.Employee;
import com.itheima.skyserver.result.PageResult;
import com.itheima.skyserver.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Employee checkLogin(Employee employee) {
        // 1. 查询用户名是否存在
        Employee loginEmp = employeeMapper.selectByUsername(employee.getUsername());
        if (loginEmp == null) throw new UsernameNotExistException("用户名不存在");

        // 2. 验证密码是否正确
        if (!Objects.equals(loginEmp.getPassword(), employee.getPassword())) throw new PasswordNotMatchException("密码错误");

        // 3. 返回结果
        return loginEmp;
    }

    @Override
    public PageResult pageQuery(String name, Integer page, Integer pageSize) {
        // 1. 开
        PageHelper.startPage(page, pageSize);

        // 2. 接
        Page<Employee> employeePage = employeeMapper.selectByCondition(name);

        // 3. 取
        return new PageResult(employeePage.getTotal(), employeePage.getResult());
    }

    @Override
    public void setStatus(Integer status, Long id) {
        employeeMapper.setStatus(status, id);
    }

    @Override
    public void insertEmployee(Employee employee) {
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.insertEmployee(employee);
    }

    @Override
    public Employee selectEmployeeById(Long id) {
        return employeeMapper.selectEmployeeById(id);
    }

    @Override
    public void updateEmployee(Employee employee) {
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.updateEmployee(employee);
    }

    @Override
    public void editPassword(String oldPassword, String newPassword) {
        Long empId = BaseContext.getCurrentId();
        log.info("修改密码信息：{}", empId);
        Employee employee = employeeMapper.selectEmployeeById(empId);
        if (employee == null) throw new UsernameNotExistException("用户不存在");
        if (!employee.getPassword().equals(oldPassword)) throw new PasswordNotMatchException("旧密码错误");
        employeeMapper.editPassword(empId, newPassword);
    }
}
